<template>
	<om-addpage style="padding-top: 35px;" :busCode="busCode" :menuName="menuName" @formSubmit="formSubmit" :showHistoryBtn="true">
		<om-autoform ref="autoform" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
	</om-addpage>
</template>
<script>
	import {
		getFormFields,
		buildFormData,
		formValidation,
		changeEditor,
		formShowLoading,
		configFormEditor,
		getWorkCacheKey,
		setSubmitSubValue,
		changeConfigAttr,
		configSelectData,
		formModelLoad,
		hasEditor,
		getEditorTitle
	} from '@/static/js/formUtil.js';
	import {ptFloat} from '@/static/js/common.js';
	import dateTimePicker from '@/static/js/dateTimePicker.js';
	import urlUtil from '@/static/js/urlUtil.js';
	import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';
export default {
	provide() {
		return {
			formPage: this
		};
	},
	data() {
		return buildFormData({
			userCacheKey: 'con-sale-trade-user-cache',
			customerCodeCacheKey:'con-sale-trade-customercode-cache',
			customerCacheKey:'con-sale-trade-customer-cache',
			initValue:{
			}
		})
	},
	computed: {
		...mapState(useLoginUserStore, ['userName', 'userId','salaryInstId','salaryInstName','salaryPosId','salaryPosName','salaryOfficeId'])
	},
	methods: {
		clearCustomerId(){
			let _that = this
			_that.$refs.autoform.clear("title1","customerId")
			_that.$refs.autoform.clear("title1","customerNameNew")
		},
		getCapitalNum(val){
			let _that = this
			_that.om.request(
				'common/getCapitalNum',
				{
					moneyNum:val
				}
			).then(res=>{
				_that.$refs.autoform.formdata.capitalAmount = res.value
			})
		},
		getWorkParam1(){
			let _that = this
			return {
				instId:_that.$refs.autoform.formdata.instId,
				instName:_that.$refs.autoform.formdata.instName
			}
		},
		clearCustomer(){
			let _that = this
			_that.$refs.autoform.clear("title1","customerId")
			_that.$refs.autoform.clear("title1","customerCodeNew")
			_that.$refs.autoform.clear("title1","customerNameNew")
			_that.$refs.autoform.clear("title1","customerShortName")
		},
		onSelectZpos(item){
		},
		clearUser() {
			let _that = this;
			_that.$refs.autoform.clear('title1', 'tradeDataUserPostId');
			_that.$refs.autoform.clear('title1', 'userId');
			_that.$refs.autoform.clear('title1', 'postId');
			_that.$refs.autoform.clear('title1', 'instId');
		},
		getCapitalPaySum(num, valueField) {
			let _that = this.$refs.autoform;
			if (_that) {
				if (num) {
					_that.om
						.request('common/getCapitalNum', {
							moneyNum: num
						})
						.then(res => {
							if (res.succeed) {
								_that.formdata[valueField] = res.value;
							}
						});
				} else {
					_that.formdata[valueField] = '';
				}
			}
		},
		onInputContractNum(item) {
			this.getCapitalPaySum(item, 'contractNumDX');
		},
		clearContractNum() {
			this.$refs.autoform.clear('title3', 'contractNum');
			this.$refs.autoform.clear('title3', 'contractNumDX');
		},
		onInputSettleNum(item) {
			if(this.$refs.autoform.formdata.taxRate){
				let businessNum = ptFloat(item) * ptFloat(this.$refs.autoform.formdata.taxRate) / 100;
				this.$refs.autoform.formdata.businessNum = businessNum
				this.getCapitalPaySum(item, 'settleNumDX');
				this.onInputBusinessNum(businessNum)
			}
		},
		clearTaxRate(){
			this.$refs.autoform.clear('title1', 'taxRate');
			this.$refs.autoform.clear('title3', 'businessNum');
			this.$refs.autoform.clear('title3', 'businessNumDX');
		},
		clearSettleNum() {
			this.$refs.autoform.clear('title3', 'settleNum');
			this.$refs.autoform.clear('title3', 'settleNumDX');
			this.$refs.autoform.clear('title3', 'businessNum');
			this.$refs.autoform.clear('title3', 'businessNumDX');
		},
		onInputExceedNum(item) {
			this.getCapitalPaySum(item, 'exceedNumDX');
		},
		clearExceedNum() {
			this.$refs.autoform.clear('title3', 'exceedNum');
			this.$refs.autoform.clear('title3', 'exceedNumDX');
		},
		onInputReceivableTaxNum(item) {
			this.getCapitalPaySum(item, 'receivableTaxNumDX');
		},
		clearReceivableTaxNum() {
			this.$refs.autoform.clear('title3', 'receivableTaxNum');
			this.$refs.autoform.clear('title3', 'receivableTaxNumDX');
		},
		onInputBusinessNum(item) {
			this.getCapitalPaySum(item, 'businessNumDX');
		},
		clearBusinessNum() {
			this.$refs.autoform.clear('title3', 'businessNum');
			this.$refs.autoform.clear('title3', 'businessNumDX');
		},
		onInputOptimizeServiceNum(item) {
			this.getCapitalPaySum(item, 'optimizeServiceNumDX');
		},
		clearOptimizeServiceNum() {
			this.$refs.autoform.clear('title3', 'optimizeServiceNum');
			this.$refs.autoform.clear('title3', 'optimizeServiceNumDX');
		},
		verifySubAdd() {
			if (!this.formdata.postId) {
				return '请选择“申请人岗位名称”';
			}
			return true;
		},
		getWorkParam() {
			return { postId: this.formdata.postId };
		},
		afterdel(editor) {
			if (!editor.workList.length) {
				editor.showAdd = true;
			}
		},
		onInputTaxRate(item){
			if(this.formdata.settleNum){
				let businessNum = ptFloat(this.formdata.settleNum) * ptFloat(item) / 100;
				this.$refs.autoform.formdata.businessNum = businessNum
				this.onInputBusinessNum(businessNum)
			}
		},
		// onInputTaxRate(val){
		// 	let _that = this
		// 	if(!val){
		// 		_that.$refs.autoform.clear("title1","taxRate")
		// 	}
		// 	if(_that.subEditorObj["title9"]){
		// 		let totalAmount = 0
		// 		let price = 0
		// 		let dataList = _that.subEditorObj["title9"].workList
		// 		for(let item of dataList){
		// 			if(item.projectId+'' === '7384'){
		// 				continue
		// 			}
		// 			if(item.projectId+'' === '7381'){
		// 				price = item.totalPrice * (Number(val || 0)) /100
		// 				totalAmount = totalAmount + price + Number(item.totalPrice)
		// 			}else{
		// 				totalAmount += Number(item.totalPrice)
		// 			}
		// 		}
		// 		_that.$refs.autoform.formdata.totalAmount = totalAmount
		// 		_that.getCapitalNum(totalAmount)
		// 		for(let item of dataList){
		// 			if(item.projectId+'' === '7384'){
		// 				item.totalPrice = price
		// 			}
		// 		}
		// 		_that.subEditorObj["title9"].workList = dataList
		// 	}
			
		// },
		formSubmit(){
			let _that = this;
			_that.formdata.updateBottomFileFlag= true
			if(Object.prototype.toString.call(_that.$refs.autoform.formdata.bottomFileList) == "[object String]"){
				_that.formdata.bottomFileListStr = _that.$refs.autoform.formdata.bottomFileList|| ''
			}else{
				_that.formdata.bottomFileListStr = JSON.stringify(_that.$refs.autoform.formdata.bottomFileList || []) || ''
			}
			delete _that.formdata.bottomFileUpload
			delete _that.formdata.bottomFileList
			if(_that.edit){
				_that.om.formSave('tradeData/doUpdate', _that.formdata, _that);
			}else{
				_that.om.formSave('tradeData/doAddByH5', _that.formdata, _that);
			}
			
		},
		initLoad(options) {
			let _that = this;
			var ajaxArr = [
				urlUtil.zposUrl(options.code), 
				{
					url:'dictSource/loadCombo',
					param:{
						sourceId:'289',
						categoryId:'6547'
					}
				}, //是否含税
				{ //结算方式
					url:'dictSource/loadCombo',
					param:{
						sourceId:'283',
						categoryId:'5843'
					}
				},
				{
					url:'tsysdict/getCombobox',
					param:{
						code: '41023',
						notInId:''
					}
				}
			];
			let fileId = options.fileId
			if(fileId){
				ajaxArr.push({
					url:'tradeData/getValue',
					param:{
						fileId:fileId
					}
				})
			}
			formModelLoad(ajaxArr, function(res, mainData) {
				changeEditor('topinfo', 'zposId', 'data', configSelectData(res[0], 'id', 'posname'), mainData);
				changeEditor('title1', 'taxTypeId', 'data', configSelectData(res[1], 'id', 'text'), mainData);
				changeEditor('title1', 'settleTypeId', 'data', configSelectData(res[2], 'id', 'text'), mainData);
				changeEditor('title1','tradeDataUserPostId',{
					"link":'../../public/searchUser/searchUser',
					"linkParam": {
						cachename: _that.userCacheKey,
						isUserPos:true,
						isSingle:true
					}
				},null,mainData)
				changeEditor(//业务人员
					'title1',
					'customerCode',
					{
						'linkParam': {
							namefield: 'customerCode',
							notefield:'customerName',
							extrafield:'contactUserName',
							searchfield: 'q',
							initload:true,
							pagination:true,
							url:'tradeData/findCustomerList',
							cachename: _that.customerCodeCacheKey,
							placeholder:"请输入顾客代码、名称"
						}
					},
					null,
					mainData
				);
				changeEditor('title1','customerId',{
					"link":'../../public/pageSearch/pageSearch',
					'linkParam': {
						other:JSON.stringify({
							userId:_that.userId
						}),
						namefield: 'customerId',
						notefield:'customerName',
						extrafield:'contactUserName',
						searchfield: 'q',
						initload:true,
						pagination:true,
						url:'customerShow/getCustomersByUserId',
						cachename: _that.customerCacheKey,
					}
				},null,mainData);
				if (_that.subEditorObj['title5']) {
					changeEditor(
						'title5',
						'userStr',
						{
							afterdel: 'afterdel',
							getWorkParam: 'getWorkParam',
							titleTemplate: '<%= userPostName %>'
						},
						null,
						mainData
					);
				}
				if (_that.subEditorObj['title6']) {
					changeEditor(
						'title6',
						'indirectUserStr',
						{
							afterdel: 'afterdel',
							getWorkParam: 'getWorkParam',
							titleTemplate: '<%= userPostName %>'
						},
						null,
						mainData
					);
				}
				if (_that.subEditorObj['title7']) {
					changeEditor(
						'title7',
						'mainUserStr',
						{
							afterdel: 'afterdel', //子表删除后调用
							getWorkParam: 'getWorkParam',
							titleTemplate: '<%= userPostName %>'
						},
						null,
						mainData
					);
				}
				if (_that.subEditorObj['title8']) {
					changeEditor(
						'title8',
						'inspectorsStr',
						{
							getWorkParam: 'getWorkParam',
							titleTemplate: '<%= userPostName %>'
						},
						null,
						mainData
					);
				}
				if (_that.subEditorObj['title9']) {
					let attr = {
						getWorkParam:'getWorkParam1'
					}
					let configData = _that.subConfigData["title9"]
					if(hasEditor('title9','projectId',configData)){
						let title = getEditorTitle("title9","projectId",configData)
						attr.titleTemplate = title+':<%= projectName  %>'
					}
					if(hasEditor('title9','totalPrice',configData)){
						let title = getEditorTitle("title9","totalPrice",configData)
						attr.subtitle1Template = title+':<%= totalPrice || "0"  %>'
					}
					
					changeEditor("title9","projectDetailStr",attr,mainData)
				}
				let tempFileList = []
				let fileUrlList = []
				changeEditor('bottominfo','bottomFileUpload','fileUploadKey',"18",mainData)
				changeEditor("bottominfo","bottomFileUpload","tempFileList", tempFileList,mainData)
				changeEditor("bottominfo","bottomFileUpload","fileUrlList", fileUrlList,mainData)
				if(fileId){
					let fieldArr = getFormFields(mainData)
					fieldArr.push('id')
					for(let index in res[4].value){
						if(fieldArr.includes(index)){
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata,index,res[4].value[index])
							_that.$set(_that.formdata,index,res[4].value[index])
						}
					}
					
				    let dataList = _that._.cloneDeep(res[4].value.inspectorsList)
					_that.subEditorObj['title8'].workList = dataList
					_that.$refs.autoform.$set(_that.$refs.autoform.formdata,'inspectorsStr',JSON.stringify(dataList))
					_that.$set(_that.formdata,'inspectorsStr',JSON.stringify(dataList))
					delete res[4].value.inspectorsList
					if(_that.subEditorObj['title9']){
						let projectDetailList = _that._.cloneDeep(res[4].value.projectDetailList)
						_that.subEditorObj['title9'].workList = projectDetailList
						_that.$refs.autoform.$set(_that.$refs.autoform.formdata,'projectDetailStr',JSON.stringify(dataList))
						_that.$set(_that.formdata,'projectDetailStr',JSON.stringify(dataList))
						delete res[4].value.projectDetailList
					}
					//处理上次保存文件
					if(_that.formdata.bottomFileList){
						let tempFileList = []
						let fileUrlList = _that.formdata.bottomFileList.map(t=>{
							tempFileList.push(t.fileSaveName)
							return t.fileSaveName
						})
						changeEditor("bottominfo","bottomFileUpload","tempFileList", tempFileList,mainData)
						changeEditor("bottominfo","bottomFileUpload","fileUrlList", fileUrlList,mainData)
					}
					changeEditor('title1','customerId',{
						"link":'../../public/pageSearch/pageSearch',
						'linkParam': {
							other:JSON.stringify({
								userId:_that.$refs.autoform.formdata.tradeDataUserPostId
							}),
							namefield: 'customerId',
							notefield:'customerName',
							extrafield:'contactUserName',
							searchfield: 'q',
							initload:true,
							pagination:true,
							url:'customerShow/getCustomersByUserId',
							cachename: _that.customerCacheKey,
						}
					},null,mainData);
				}else{
					if(_that.subEditorObj['title9']){
						let subMainData = _that.subConfigData["title9"]
						let fieldArr = getFormFields(subMainData)
						let arr = []
						for(let index in res[4]){
							let obj = {}
							for(let index in fieldArr){
								_that.$set(obj,fieldArr[index],'')
							}
							if(res[4][index].id){
								_that.$set(obj,'projectId',res[4][index].id)
								_that.$set(obj,'projectName',res[4][index].dicname)
							}
							arr.push(obj)
						}
						_that.subEditorObj["title9"].workList = arr
					}
				
				}
				_that.$nextTick(function(){
					if(!_that.$refs.autoform.formdata.zposId){
						_that.$refs.autoform.initSelectVal('topinfo','zposId')
					}else{
						_that.$refs.autoform.initSelectIndex('topinfo','zposId')
					}
					_that.$refs.autoform.initSelectIndex("title1","taxTypeId")
					_that.$refs.autoform.initSelectIndex("title1","settleTypeId")
				})
			}, options);
		}
	},
	onLoad(options) {
		let _that = this;
		if(_that.salaryOfficeId){
			_that.initValue.tradeDataUserPostId = this.salaryOfficeId;
			_that.initValue.userId = this.userId;
			_that.initValue.userName = this.userName
			_that.initValue.postId = this.salaryPosId;
			_that.initValue.postName = this.salaryPosName
			_that.initValue.instId = this.salaryInstId;
			_that.initValue.instName = this.salaryInstName
		}
		_that.initValue.userId = this.userId;
		_that.initValue.userName = this.userName
		_that.initValue.postId = this.salaryPosId;
		_that.initValue.postName = this.salaryPosName
		_that.initValue.instId = this.salaryInstId;
		_that.initValue.instName = this.salaryInstName
		_that.initLoad(options);
	},
	onShow() {
		let _that = this;
		if (_that.$refs.autoform) {
			for (var fieldId in _that.subEditorObj) {
				var editor = _that.subEditorObj[fieldId];
				uni.getStorage({
					key: getWorkCacheKey(fieldId),
					success: function(res) {
						if (['title5', 'title6', 'title7'].includes(fieldId) && res.data.length) {
							editor.showAdd = false;
						} else {
							editor.showAdd = true;
						}
						if(fieldId == 'title9'){
							let totalAmount = 0
							let price = 0
							let hasVal = false
							for(let d of res.data){
								if(d.projectId+'' === '7384' && d.totalPrice){
									hasVal = true
								}
							}
							for(let item of res.data){
								if(_that.$refs.autoform.formdata.taxRate){
									if(item.projectId+'' === '7384' && !hasVal){
										continue
									}
									if(item.projectId+'' === '7381'){
										price = item.totalPrice * (_that.$refs.autoform.formdata.taxRate) /100
										if(hasVal){
											totalAmount += Number(item.totalPrice)
										}else{
											totalAmount = totalAmount + price + Number(item.totalPrice)
										}
									}else{
										totalAmount += Number(item.totalPrice)
									}
								}else{
									totalAmount += Number(item.totalPrice)
								}
							}
							_that.$refs.autoform.formdata.totalAmount = totalAmount
							_that.getCapitalNum(totalAmount)
							for(let item of res.data){
								if(item.projectId+'' === '7384' && !item.totalPrice){
									item.totalPrice = price
								}
							}
						}
						editor.workList = res.data;
						uni.removeStorage({
							key: getWorkCacheKey(fieldId)
						});
					}
				});
			}
			uni.getStorage({
				key: _that.userCacheKey,
				success: function(res) {
					if (res.data) {
						let d = res.data[0];
						var formdata = _that.$refs.autoform.formdata;
						formdata.tradeDataUserPostId = d.id;
						formdata.userName = d.username;
						formdata.postId = d.posId;
						formdata.postName = d.posName;
						formdata.instId = d.instId;
						formdata.instName = d.instName;
						_that.$refs.autoform.changeEditor('title1','customerId',{
							"link":'../../public/pageSearch/pageSearch',
							'linkParam': {
								other:JSON.stringify({
									userId:d.id
								}),
								namefield: 'customerId',
								notefield:'customerName',
								extrafield:'contactUserName',
								searchfield: 'q',
								initload:true,
								pagination:true,
								url:'customerShow/getCustomersByUserId',
								cachename: _that.customerCacheKey,
							}
						});
						_that.clearCustomer()
						uni.removeStorage({
							key: _that.userCacheKey
						});
					}
				}
			});
			uni.getStorage({
				key: _that.customerCodeCacheKey,
				success: function(res) {
					if (res.data) {
						let d = res.data;
						var formdata = _that.$refs.autoform.formdata;
						if(Object.prototype.toString.call(d) == '[object Object]'){
							formdata.customerCode = d.customerCode;
							formdata.customerName = d.customerName;
							formdata.contactUserName = d.contactUserName;
							formdata.contactWay = d.contactWay;
							formdata.otherRemark = d.otherRemark;
						}else{
							formdata.customerCode = d
							formdata.customerName = ''
							formdata.contactUserName = ''
							formdata.contactWay = ''
							formdata.otherRemark = ''
						}
						uni.removeStorage({
							key: _that.customerCodeCacheKey
						});
					}
				}
			});
			uni.getStorage({
				key:_that.customerCacheKey,
				success:(res)=>{
					if(res.data){
						let d = res.data
						let formdata =  _that.$refs.autoform.formdata
						formdata.customerId = d.id
						formdata.customerIdCoding = d.customerCode
						formdata.customerCodeNew = d.customerId
						formdata.customerNameNew = d.customerName
						formdata.customerShortName = d.customerShortName
						uni.removeStorage({
							key:_that.customerCacheKey
						})
					}
				}
			})
		}
	}
};
</script>
<style></style>
